package com.middle.common.util;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public final class GsonUtil {

	private GsonUtil() {
	}

	private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create();

	public static String toJson(Object obj) {
		if (obj == null) {
			throw new NullPointerException("parse the object is null");
		}
		return GSON.toJson(obj);
	}

	public static <T> T toObject(String json, Class<T> clazz) {
		if (json == null || json.trim().length() == 0) {
			throw new NullPointerException("the string is null");
		}
		return GSON.fromJson(json, clazz);
	}

	public static <T> List<T> toList(String json, Class<T> clazz) {
		if (json == null || json.trim().length() == 0) {
			throw new NullPointerException("the string is null");
		}
		List<T> list = new ArrayList<>();
		JsonElement elements = JsonParser.parseString(json);
		if (elements.isJsonArray()) {
			JsonArray array = elements.getAsJsonArray();
			for (JsonElement element : array) {
				T object = GSON.fromJson(element, clazz);
				list.add(object);
			}
		} else if (elements.isJsonObject()) {
			T object = GSON.fromJson(elements, clazz);
			list.add(object);
		} else {
			throw new ClassCastException("the string Can not be converted to object");
		}
		return list;
	}

}
